Skip to content

Infer loop invariants for the int locals a loop changes (Houdini) - #551

Merged
CatarinaGamboa merged 2 commits into
mainfrom
feat/544-houdini-loop-invariants
Nov 23, 2026
Merged

CatarinaGamboa merged 2 commits into
mainfrom
feat/544-houdini-loop-invariants

Conversation

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator

Stacked on #550; review/merge after it.

Fixes #544
Fixes #537
Fixes #479

Part of the loop invariant inference plan (#542).

What and why

A loop havocs every variable it changes: at the loop head a changed variable keeps only its declared refinement, so for (int i = 0; i < 10; i++) use(i) did not know i >= 0 (#537). This PR infers invariants for the int local variables (and parameters) a loop changes, with the Houdini algorithm (Flanagan and Leino, FME 2001) over the candidates of #550 (Liquid Types qualifiers):

  1. Start check (new LoopInvariants, before the havoc): keep the candidates that the facts before the loop prove (x0 is the instance before the loop).
  2. Assume at the head (startIteration): add the remaining candidates to the refinements of the loop-head instances (not as a path condition, which an assignment would rename or drop).
  3. Step check (recordNextIteration): at the point where the next iteration starts (end of the body for while/for-each, after the update for for, after the condition for do-while, where the condition is now assumed since the next iteration only starts when it holds) drop each candidate not proved for the last instances.
  4. Continues: the end of a body with continues is a join where scanBody havocs the changed variables again. There, the candidates and "x grew / shrank since the head" are kept when proved at every continue and at the fall-through end of the body (atJoin/joined), so a for update or a do-while condition that follows can still be checked.
  5. Repeat until a check drops nothing, inside the existing checkUntilFixpoint loop (which already re-checks the body until typestates are stable and keeps only the errors of the last check). After 8 checks that dropped candidates, all are dropped (MAX_ROUNDS).

All candidate proofs are silent (checkStateSMT(..., silent = true)); a failed or unknown proof only drops the candidate. Loops whose jumps run a finally or leave a labelled block (followsJumps false) infer nothing, as their typestates are not followed either.

Soundness argument

A candidate survives only if (a) it is proved from the facts before the loop, and (b) in the last check, assuming all survivors at the head, it is proved at every point where the next iteration starts: the end of the body (if reachable), the update or condition after it, and every continue (through the join facts, each proved on every path into the join). So the survivors form an inductive invariant and hold at the head on every iteration; errors are only kept from that last check. An earlier check assumes more candidates (and fewer typestates) than the last one, so an error that stops it is also an error of the last one. Integers are mathematical, as elsewhere in LiquidJava.

Checked with Codex (no false negative found) and these programs that must still be rejected: decrementing counter with _ >= 0, counter reset in the body, i = i - 2 on some path, a bound the step breaks (i += 3 under i < 10 with _ <= 10), a continue path that decreases i (in while, and in for before the update), an inner loop that decreases the outer counter, labelled continue from an inner loop, switch and try/finally in the body.

Before / after

Program main this PR
#537 for (int i = 0; i < 10; i++) use(i) found i < 10 but expected i >= 0 Correct
#537 while (total < 1024) { use(total); total = total + 1; } found total < 1024 but expected total >= 0 Correct
#537 buffer loop (read(buf, total, limit - total) with off >= 0, if (n < 0) break; total += n;) found total < limit but expected total >= 0 Correct
#538 bounded accumulation (@Refinement("_ >= 0 && _ <= 1024") total, guard then total = total + n) Refinement Error Correct (with #549)
#479 for (int i = 0; i < l.size(); i++) l.get(i) ... i < #size_result but expected i >= 0 && i < size(l) Correct

#479 needed only i >= 0: the list is not havocked (its size() and get do not change its state), so the plan's #546 (candidates from what the body requires) is not needed for it.

Tests

Timing

Full suite, same machine, two runs each (machine shared, so noisy): main 195 s / 170 s wall, TestExamples 127 s / 86 s; this PR 163 s / 142 s wall, TestExamples 98 s / 91 s. On the same pair of runs, the 16 existing loop fixtures take 1.3 to 2 times as long (e.g. CorrectLoopStateFixpoint 2.3 s to 3.6 s, CorrectLoopCondition 0.37 s to 0.79 s): each check of a loop body now also runs one silent SMT query per candidate, and a dropped candidate costs one more check of the body. Tuning (caps, nested loops re-inferred per outer check) is #547.

Known precision gaps (from the Codex review, left for later)

  • A for update or do-while condition that repairs a value set before a continue (i = -1; continue; then i++) is not followed: the join keeps only facts proved before the update.
  • A finally anywhere on a jump path turns inference off for the whole loop, as for typestates.

🤖 Generated with Claude Code

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

I found no false negative in the programs I ran. The branch reported refinement errors for the tested decrements, resets, continue paths, nested loops, switch paths, and try/finally path. It verified the ordinary counter examples that the pre-PR build rejects.

  1. False positive — a for update repairs a value after continue. In Repair.java, i starts at 0. The continue path sets it to −1, then the for update increments it to 0 before the next body execution:

    static void nonneg(@Refinement("_ >= 0") int x) {}
    static boolean choice() { return true; }
    static void forRepair() {
      for (int i = 0; i < 10; i++) {
        nonneg(i);
        if (choice()) { i = -1; continue; }
      }
    }

    Observed: Refinement Error: found i < 10 && i <= 10 but expected i >= 0 at nonneg(i). LoopInvariants.recordContinue intersects candidate facts before the update. Fix: join continue states before the update, but test inductiveness after executing the update on each joined path.

  2. False positive — a do-while condition repairs a value after continue. Repair.java also contains:

    static void doRepair() {
      int i = 0;
      do {
        nonneg(i);
        if (choice()) { i = -1; continue; }
        i++;
      } while (i++ < 10);
    }

    The condition increments −1 to 0 before the next body execution. Observed: Refinement Error: expected i >= 0 but could not prove it at nonneg(i). Fix: preserve the continue paths through evaluation of the condition, then check candidates at the next loop head. The true-condition assumption must remain scoped to that back edge.

  3. False positive — harmless finally disables inference for the whole loop. In FinallyPrecision.java:

    static void nonneg(@Refinement("_ >= 0") int x) {}
    static void f() {
      for (int i = 0; i < 10; i++) {
        nonneg(i);
        try { continue; } finally { int x = 0; }
      }
    }

    Observed: Refinement Error: found i < 10 but expected i >= 0. visitLoop sets all tracked locals aside when followsJumps sees cleanup. Fix: account for writes made by cleanup and retain inference for locals it cannot change.

Code quality: scanBody searches for any nested continue, including one targeting another loop; filtering by jump target would avoid unnecessary joins and havoc. The repository was not modified.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex round 1: what was done

No false negative found. The three findings are precision gaps; all declined for this PR and listed in the PR body under "Known precision gaps":

  1. for update that repairs a value set before a continue: following it needs the update checked once per continue path (or the join to keep relational facts beyond "grew/shrank since the head"). This is a rare pattern; it fits the tuning step (Invariant inference 5/6: cost caps and nested loops #547) if it shows up in the study exercises.
  2. Same for a do-while condition with a side effect after a continue.
  3. A finally on a jump path turning inference off: kept consistent with the typestate tracking, which uses the same followsJumps rule; refining both is a separate change.

Code quality (scanBody joins for a continue that targets an inner loop): declined here, as this havoc predates the PR and also drives the typestate join; filtering by target changes typestate behaviour too. Noted for #547.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

No false negative found in round 2. I compiled the branch once and ran the adversarial programs under codex544. No repository files were changed.

  1. Relational candidates: RelationalBroken.java changes both variables before calling a refined method:

    while (i < j && j > -10) {
      i += 2;
      j -= 2;
      need(j - i); // requires >= 0
    }

    Observed: Refinement Error at this call and at the analogous i + j case. The compiled origin/main also reports both errors. No fix indicated.

  2. Control flow and scopes: Nested.java, Controls.java, Scopes.java, and MoreEdges.java exercise nested and labelled continues, switch fall-through, try/catch continues, constructors, parameters, lambdas, do-while, side-effecting conditions, for updates, and for-each loops. Each deliberately violated @Refinement("_ >= 0") produced a Refinement Error. No fix indicated.

I found no new code-quality issue material to this review.

No false negative in two rounds; the Codex loop for this PR ends here.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit of this PR's own new code (LoopInvariants and its wiring in RefinementTypeChecker), clean-code-principles.

  • [solid-srp] LoopInvariants holds the Houdini state of one loop (candidates, rounds, join facts) with the same lifecycle hooks as LoopTypestates (startIteration, recordContinue, endBody, recordNextIteration, reachedFixpoint). OK; mirroring that class keeps the two fixpoints readable side by side.
  • [func-no-side-effects] addToLastInstances mutates the refinements of the head and join instances. Declined: intended (an instance's refinement, unlike a path condition, is not renamed or dropped by assignments); the original refinement is kept in declared so each check rebuilds it from the current candidates.
  • [core-dry] Parallel structures loops (typestates) and invariants (map by loop). Declined: merging them into one record would touch every existing use of loops; a map keeps this PR small.
  • [core-dry] The int test exists twice: RefinementTypeChecker.isIntVariable (context type, to pick the variables) and InvariantCandidates.isIntLocal (Spoon declaration, to pick terms). Declined: they answer different questions on different inputs.
  • [name-meaningful] checkUntilFixpoint evaluates both fixpoints before testing them (typestatesStable), since reachedFixpoint grows the head states. OK, named for that reason.
  • [name-searchable] MAX_ROUNDS = 8 is named and documented. OK.

@CatarinaGamboa
CatarinaGamboa force-pushed the feat/544-houdini-loop-invariants branch from 800c30e to 3775ff5 Compare November 23, 2026 17:18
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/543-invariant-candidates branch from 2bd898a to ddbe7c3 Compare November 23, 2026 17:18
@CatarinaGamboa
CatarinaGamboa changed the base branch from feat/543-invariant-candidates to main November 23, 2026 17:30
CatarinaGamboa and others added 2 commits November 23, 2026 17:30
A loop forgot everything about the int locals it changes but their
declared refinements, so for (int i = 0; i < 10; i++) use(i) did not know
i >= 0. With the Houdini algorithm, the candidate invariants that the
facts before the loop prove are added to the instances at the loop head;
each check of the body drops those not proved where the next iteration
starts (end of the body, after a for's update, after a do-while's
condition, which now holds there), until none is dropped, within the
loop that already re-checks the body until its typestates are stable.
The candidate proofs are silent. Where continues join at the end of the
body, the candidates and whether each variable grew or shrank since the
head are kept when proved at every continue and at the end of the body.
After 8 checks that dropped candidates, all are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa
CatarinaGamboa force-pushed the feat/544-houdini-loop-invariants branch from 3775ff5 to cfc266a Compare November 23, 2026 17:30
@CatarinaGamboa
CatarinaGamboa merged commit 3e46ea2 into main Nov 23, 2026
1 check passed
CatarinaGamboa added a commit that referenced this pull request Nov 23, 2026
…eak (#552)

Stacked on #551; review/merge after it.

Fixes #545

Part of the loop invariant inference plan (#542).

## What and why
After a loop, the variables it changes were havocked again: only their
declared refinements were known, so after `int i = 0; while (i < n)
i++;` nothing said `i >= n`. Now, after a loop that can only exit at its
head through its condition, the instances after the loop get the
invariants inferred in #551 and the negated condition:
- `exitsAtHeadThroughCondition`: a `while`, `for` or for-each loop (not
a `do`-`while`), with no `break` whose target is the loop (labelled or
not), and a condition that writes no variable.
- `InvariantCandidates.condition` translates the condition when it is
built of `&&`, `||`, `!` and comparisons (`<`, `<=`, `>`, `>=`, `==`,
`!=`) of the terms a candidate may mention (int literals, int locals and
parameters, `+`, `-`, `*`); otherwise only the invariants are added.
- `LoopInvariants.afterLoop` adds them to the post-loop instances (after
the existing havoc), like the head facts.

Also (found by the Codex review): `TryChecker` starts a catch block from
any value a variable had in the try block, including values recorded in
loop-body checks that name join instances of a dropped check. The
post-loop instance used to be `true`, which hid them; with facts after
the loop they surfaced as `Variable #i_11 could not be found` (already
the case on main for a refined variable). The variable is now unknown in
the catch block when such a value is among them.

## Soundness argument
- The invariants hold at the loop head on every visit (#551), including
the last one, where the condition is evaluated to false and the loop
exits.
- For `while`/`for` without `break`, the code after the loop is reached
only from that point (a `return`, `throw` or labelled jump to an outer
statement does not reach it), and the condition writes nothing, so the
state after the loop is the head state where the condition was false:
the invariants and the negated condition describe it.
- A `do`-`while` exits after its body and condition, where the head
invariants need not hold (`do { i = i + 5; } while (i < 3);` keeps `i <=
3` at the head but exits with `i == 5`), so it is excluded. A condition
with a side effect (`while (i++ < 10)`) exits in a state after the head,
so it is excluded too.
- The negated condition is built from the same Java expression with pure
terms only, so it means what the condition meant at the exit.
- Making a variable unknown in a catch block only removes facts.

## Before / after
`int i = 0; while (i < n) i++; atLeast(i, n);` (`@Refinement("_ <= i")
int n`): before `Refinement Error` (only `i`'s declared refinement
known), after `Correct`.
`for (; i < 10; i++) { if (next()) continue; } ten(i);` (`_ == 10`):
before `Refinement Error`, after `Correct` (invariant `i <= 10` and `!(i
< 10)`).

## Tests
- `CorrectLoopExitFacts` (the first two fail on #551 alone): `i >= n`
after counting up with `while`; `i == 10` after a `for` whose body has a
continue; a loop in a try with a catch (spurious `Not Found Error`
without the `TryChecker` change).
- `ErrorLoopExitFacts`: no negated condition after a loop with `break`;
none after a `do`-`while` (the example above); none after a condition
that increments (`while (i++ < 10)` exits with `i == 11`).
- `InvariantCandidatesTest.translatesConditionsOverTheSameTerms`: `!`,
`||`, `&&`, `==`, `!=` translated; conditions with calls or a literal
`true` not.

Full suite passes locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant